<template>
  <mu-h-box class="step-box" size="auto" @click.native="clickStep">
    <mu-v-box v-if="!readonly" style="min-width:60px;"
      align-items="center" justify-content="center" border-right>
      <input
        v-model="check"
        :disabled="rebar"
        class="checkbox"
        type="checkbox"
        name="checkbox"
        @change="checkChange">
    </mu-v-box>

    <mu-v-box size="200px" border-right>
      <mu-bar class="pad-4" border-bottom>
        <div style="height:31px;line-height:31px;">{{ name }}</div>
      </mu-bar>
      <mu-bar class="pad-4">
        <mu-editor
          v-model.trim="remark"
          :disabled="readonly||rebar"
          :placeholder="`${readonly||rebar?'- -':'请输入使用说明'}`"
          :class="`border-dashed ${isActive?'active':''}`"
          @input="handleRemarkChange" />
      </mu-bar>
    </mu-v-box>

    <mu-v-box size="auto" class="pad-4" border-right>
      <textarea
        ref="formula"
        v-model.trim="formula"
        :disabled="readonly"
        :class="`mu-input textarea border-dashed ${isActive?'active':''}`"
        :readonly="readonly"
        :placeholder="`${readonly?'- -':'请输入公式内容'}`"
        @focus="handleFormulaFocus"
        @blur="handleFormulaBlur"
        @input="handleFormulaChange" />
    </mu-v-box>

    <mu-v-box size="200px" border-right>
      <mu-bar class="pad-4" border-bottom>
        <div style="height:31px;line-height:31px;">
          计算结果：{{ result }}
        </div>
      </mu-bar>
      <mu-bar class="pad-4">
        <mu-combo-box
          v-model="digit"
          class="border-dashed"
          :options="digitOptions"
          :disabled="readonly"
          :clearable="false"
          @change="handleDigitChange" />
      </mu-bar>
    </mu-v-box>
    <mu-v-box v-if="showUnit" size="80px" style="min-width:80px;" class="pad-4">
      <input
        v-model.trim="unit"
        class="mu-input textarea border-dashed"
        style="text-align: center;"
        :placeholder="`${readonly?'- -':'输入单位'}`"
        :disabled="readonly"
        @input="handleUnitChange">
    </mu-v-box>
  </mu-h-box>
</template>

<script>
  import debounce from 'lodash.debounce'
  export default {
    props: {
      step: {
        type: Object,
        required: true
      },
      readonly: {
        type: Boolean,
        default: false
      },
      rebar: {
        type: Boolean,
        default: false
      },
      allNames: {
        type: Array,
        default: () => ([])
      },
      checked: {
        type: Boolean,
        default: false
      },
      isActive: {
        type: Boolean,
        default: false
      },
      showUnit: {
        type: Boolean,
        default: true
      }
    },
    data () {
      return {
        unit: '',
        name: '',
        remark: '',
        formula: '',
        digit: null,
        timer: null,
        digitOptions: [
          { value: 'default', label: '默认' },
          { value: 'round', label: '四舍五入取整' },
          { value: 'floor', label: '向下取整' },
          { value: 'ceil', label: '向上取整' },
          { value: 'double1', label: '1位小数' },
          { value: 'double2', label: '2位小数' },
          { value: 'double3', label: '3位小数' },
          { value: 'double4', label: '4位小数' },
          { value: 'double5', label: '5位小数' },
          { value: 'rebarspecial', label: '常用设置' }
        ],
        startIndex: 0,
        endIndex: 0,
        isFocus: false
      }
    },

    computed: {
      check: {
        get () {
          return this.checked
        },
        set (value) {
          this.$emit('checked', {
            ...this.step,
            checked: value
          })
        }
      },
      result () {
        const result = this.step.result
        return result === null ? '（无）' : result
      },
      readonlyOrRebar () {
        return this.readonly || this.rebar
      }
    },

    mounted () {
      this.initForm()
    },

    methods: {
      updateStep (val) {
        this.$emit('update', val)
      },

      handleFormulaBlur () {
        const element = this.$refs.formula
        this.startIndex = element.selectionStart
        this.endIndex = element.selectionEnd
      },

      checkChange (event) {
        const { checked } = event.target
        this.updateStep({ ...this.step, checked })
      },

      handleDigitChange (val) {
        this.updateStep({ ...this.step, digit: val })
      },

      handleFormulaChange: debounce(function (event) {
        this.updateStep({ ...this.step, formula: event.target.value })
      }, 300),

      handleRemarkChange: debounce(function () {
        if (this.remark === this.step.remark) {
          return
        }
        this.updateStep({ ...this.step, remark: this.remark })
      }, 300),

      handleUnitChange: debounce(function () {
        if (this.unit === this.step.unit) {
          return
        }
        this.updateStep({ ...this.step, unit: this.unit })
      }, 300),

      handleFormulaFocus (event) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.isFocus = true
        this.$emit('active', this.step.id)
      },

      clickStep (event) {
        this.$emit('selected', this.step.id)
        if (!this.isActive) {
          this.$emit('active', this.step.id)
        }
      },

      insert (strToInsert) {
        const startIndex = this.isFocus ? this.startIndex : this.formula.length
        const endIndex = this.isFocus ? this.endIndex : this.formula.length

        const position = startIndex + strToInsert.length

        const formula = this.formula ? this.formula.slice(0, startIndex) +
          strToInsert + this.formula.slice(endIndex) : strToInsert

        const element = this.$refs.formula

        setTimeout(() => {
          element.focus()
          element.setSelectionRange(position, position)
        }, 10)

        this.formula = formula

        this.updateStep({ ...this.step, formula })
      },

      initForm () {
        const { name = '', remark = '', formula = '', digit = 'default', unit = '' } = this.step
        this.name = name
        this.remark = remark
        this.formula = formula
        this.digit = digit
        this.unit = unit
      },

      checkboxChange (event) {
        this.$emit('checked', {
          ...this.step,
          checked: event.target.checked
        })
      }
    }
  }
</script>

<style scoped>
  textarea.mu-input {
    min-height: 60px;
    font-family: inherit;
  }

  .flex-box .step-result {
    line-height: 16px;
  }

  .border-dashed >>> input {
    border: none !important;
  }

  .textarea {
    width: 100%;
    height: 71px !important;
    min-height: 71px !important;
    max-height: 71px !important;
    padding: 8px;
    margin: 0px;
    display: inline-block;
    border: none !important;
  }

  .textarea.active {
    background-color: #f4fbff !important;
  }

  .textarea.active:focus {
     background-color: #fff !important;
  }

  .step-box >>> .mu-input[disabled] {
    background-color: #fff;
    border-color: #d9d9d9;
    color: #333333;
    box-shadow: none;
  }

  .border-dashed:not([disabled]) {
    border: 1px dashed #ccc !important;
    border-radius: 2px !important;
  }

  .active >>> input {
     background-color: #f4fbff !important;
  }

  .active >>> input:focus {
     background-color: #fff !important;
  }

  input[type=checkbox]:not([disabled]) {
    cursor: pointer;
    position: relative;
  }

  input[type=checkbox]::after {
    position: absolute;
    top: 0;
    background-color: #fff;
    color: #fff;
    width: 14px;
    height: 14px;
    display: inline-block;
    visibility: visible;
    padding-left: 0px;
    text-align: center;
    content: ' ';
    border-radius: 2px;
    box-sizing: border-box;
    border: 1px solid #ddd;
  }

  input[type=checkbox][disabled]::after {
    background-color: #eeeeee;
  }

  input[type=checkbox]:checked::after {
    content: "";
    background-color: #037DF3;
    border-color: #037DF3;
    background-color: #037DF3;
  }

  input[type=checkbox]:checked::before {
    content: '';
    position: absolute;
    top: 1px;
    left: 5px;
    width: 3px;
    height: 8px;
    border: solid white;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg);
    z-index: 1;
  }
</style>
